<template>
  <el-dialog width="1200px" :title="$t('m.initInventory.information')" :visible.sync="dialogVisible" :before-close="close" :close-on-click-modal="false">
    <formBrief></formBrief>
    <el-divider>{{$t('m.inventory.details')}}</el-divider>
    <template v-if="stocktype===1">
      <skuTable ref="skuTable" @isProhibited="setSaveBtn"></skuTable>
    </template>
    <template v-if="stocktype===2">
      <locationTable ref="locationTable" @isProhibited="setSaveBtn"></locationTable>
    </template>
    <template v-if="stocktype===3">
      <collisionTable ref="collisionTable" @isProhibited="setSaveBtn"></collisionTable>
    </template>

    <template v-if="stocktype===4">
      <warningTable ref="warningTable" @isProhibited="setSaveBtn"></warningTable>
    </template>

    <template v-if="stocktype===5">
      <ageTable ref="ageTable" @isProhibited="setSaveBtn"></ageTable>
    </template>

    <el-row>
      <el-button v-if="state!==1" type="primary" @click="validate(1)" :loading="btnLoading" :disabled="btnDisabled">{{$t('m.submit')}}</el-button>
      <el-button v-if="state!==1" type="primary" @click="validate(0)" :loading="btnLoading" :disabled="btnDisabled">{{$t('m.save')}}</el-button>
      <el-button @click="close">{{$t('m.close')}}</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import formBrief from '@/components/initialInventory/inventory-form-brief'
export default {
  name:'initial-inventory-popup',
  props:['dialogVisible','extraInventoryType'],
  data(){
    return {
      stocktype:0, // 盘点类型
      state:'',
      condition:'', // 预警库存、库龄盘点条件

      btnDisabled:false,
      btnLoading:false // 控制按钮loading，防止重复提交
    }
  },
  inject:{
    getFormInfo:{
      default:()=>{}
    },
    getInventoryTableList:{
      default:()=>[]
    },
    getInventoryDetail:{
      default:()=>{}
    }
  },
  mounted(){
    this.stocktype = this.getInventoryDetail()?this.getInventoryDetail().stocktype:this.getFormInfo().stocktype
    this.stockway = this.getInventoryDetail()?this.getInventoryDetail().stockway:this.getFormInfo().stockway
    this.state = this.getInventoryDetail()?this.getInventoryDetail().state:this.getFormInfo().state
  },
  components:{
    formBrief,
    // 这块用组件懒加载
    skuTable:()=>import('@/components/initialInventory/sku/inventory-sku-table'), // sku盘点组件
    locationTable:()=>import('@/components/initialInventory/location/inventory-location-table'), // 库位盘点组件
    collisionTable:()=>import('@/components/initialInventory/collision/inventory-collision-table'), // 动碰盘点组件
    warningTable:()=>import('@/components/initialInventory/warning/inventory-warning-table'), //预警库存盘点组件
    ageTable:()=>import('@/components/initialInventory/warehouseAge/inventory-age-table') //库龄盘点组件
  },
  methods:{
    close(){
      this.$emit('close')
    },
    // 设置保存按钮disabled状态(@focus时，按钮不可点击)
    setSaveBtn(status){
      this.btnDisabled = status
    },
    validate(flag){
      let {tableRefs,uniqueCode} = this.getInventoryTableList().find((item)=>{
        return item.stocktype === this.stocktype
      })
      let tableData = this.cloneObject(this.$refs[tableRefs].tableData) || []
      let warehouseid = this.$store.state.basicInfo.warehouseInfo.id
      if(!this.getInventoryDetail()){
        if(this.stocktype===4){
          this.condition = this.extraInventoryType.warning.join('')
        }
        if(this.stocktype===5){
          this.condition = `>${this.extraInventoryType.storageAge.join('')}天`
        }
      }else{
        this.condition = this.getInventoryDetail().condition
      }
      let data = {
        warehouseid,
        stocktype:this.stocktype,
        stockway:this.stockway,
        initialstocktakeid:this.getInventoryDetail().initialstocktakeid,
        state:this.state,
        condition:this.condition
      }
      if([1,2].includes(this.stocktype)){ // sku && 库位盘点
        // 判断是否有空的sku or locationcode
        for(let i=0;i<tableData.length;i++){
          if(!tableData[i][uniqueCode]){
            return this.callbackMessage(this.$t('m.inventory.all'))
          }
        }
        tableData = tableData.map((item)=>{
          item.skuDisabledChange && delete item.skuDisabledChange
          return item
        })
      } else {
        if(!tableData.length) return this.callbackMessage(this.$t('m.inventory.detailError'))
        if(!this.getInventoryDetail()){
          tableData.forEach((item)=>{ // 动碰盘点需要处理下数据
            let storage = item.productstocksum
            delete item.productstocksum
            Object.assign(item,{storage})
          })
        }

        if(this.stocktype===3){ // 单独针对动碰盘点进行处理
          let partitionids = this.$refs[tableRefs].formInline.partitionList
          let {createdatestart:touchstartdate,createdateend:touchenddate} = this.$refs[tableRefs].datetimerange
          Object.assign(data,{partitionids,touchstartdate,touchenddate})
        }
      }
      Object.assign(data,{initialstockTakeDetailInputList:tableData})
      flag===0?this.save(data):this.submit(data)
    },

    save(data){
      let options = !this.getInventoryDetail()
        ? { method:'post', url:'/initialstocktake/add', data }
        : {
          method:'put',
          url:`/initialstocktake/${this.getInventoryDetail().initialstocktakeid}`,
          data
        }
      this.btnLoading = true
      this.$axios(options).then(() => {
        this.btnLoading = false
        this.callbackMessage(this.$t('m.quality.success'),'success')
        this.$emit('callback')
        this.$emit('close')
      }).catch(()=>{
        this.btnLoading = false
      })
    },
    submit(data){
      let {tableRefs,uniqueCode} = this.getInventoryTableList().find((item)=> item.stocktype === this.stocktype)
      let tableData = this.cloneObject(this.$refs[tableRefs].tableData) || []
      // 筛选出所有库位并去重
      let locationid = tableData.reduce((prev,next)=>{
        prev.push(next.locationid)
        return prev
      },[])
      let options = {
        method:'post',
        url:`/initialstocktake/getareacount`,
        data:locationid
      }
      this.btnLoading = true
      // 库位是否在不同的区域，如在不同区域，则提示
      this.$axios(options).then(({data:isDifferentArea}) => {
        // console.log(isDifferentArea)
        if(isDifferentArea>1){
          this.$confirm(this.$t('m.initInventory.tips3')+`${isDifferentArea}`+this.$t('m.initInventory.tips4'), this.$t('m.noticemessage'), {
            confirmButtonText:this.$t('m.confirm'),
            cancelButtonText:this.$t('m.cancel'),
            type:'warning'
          }).then(() => {
            let options ={
              method:'post',
              url:'/initialstocktake/commit',
              data
            }
            this.$axios(options).then(() => {
              this.btnLoading = false
              this.callbackMessage(this.$t('m.quality.success'),'success')
              this.$emit('callback')
              this.$emit('close')
            }).catch(()=>{
              this.btnLoading = false
            })
          }).catch(() => {
            this.btnLoading = false
          })
        }else{
          let options = {
            method:'post',
            url:'/initialstocktake/commit',
            data
          }
          this.$axios(options).then(() => {
            this.btnLoading = false
            this.callbackMessage(this.$t('m.quality.success'),'success')
            this.$emit('callback')
            this.$emit('close')
          }).catch(()=>{
            this.btnLoading = false
          })
        }
      }).catch(()=>{
        this.btnLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-divider__text{font-size: 18px;}
</style>